<?php


namespace catchAdmin\product\controller;


use catchAdmin\product\model\Unit as UnitModel;
use catchAdmin\product\request\UnitCreateRequest;
use catcher\base\CatchController;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\Utils;

class Unit extends CatchController
{
    protected $unit;

    public function __construct(UnitModel $unit)
    {
        $this->unit = $unit;
    }

    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->unit->getList($user['tenant_id']));
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function getUnit(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->unit->getAttrList($user['tenant_id']);
        return CatchResponse::success($list->toArray(), '查询成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function create(CatchAuth $auth,UnitCreateRequest $request)
    {
        $params = $request->param();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['unit_code'] = date('YmdHis').$user['tenant_id'];
        $this->unit->storeBy($params);
        return CatchResponse::success('', '新建成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function update(UnitCreateRequest $request)
    {
        $params = $request->filterEmptyField()->param();
        $id = $params['id'];
        $this->unit->updateBy($id, $params);
        return CatchResponse::success('', '编辑成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $ids = Utils::stringToArrayBy($id);
        foreach ($ids as $_id) {
            $this->unit->deleteBy($_id);
        }
        return CatchResponse::success('', '删除成功');
    }
}